<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right" style="font-size: 16px;">
      <el-breadcrumb-item :to="{ path: '/sys-admin' }">
        <i class="el-icon-s-promotion"></i> 后台管理
      </el-breadcrumb-item>
      <el-breadcrumb-item>新增SPU</el-breadcrumb-item>
      <el-breadcrumb-item>第1步：选择类别</el-breadcrumb-item>
    </el-breadcrumb>

    <el-divider></el-divider>

    <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="130px" class="demo-ruleForm">
      <el-form-item label="商品类别" prop="categoryId">
        <el-input v-model="ruleForm.categoryId" placeholder="请输入类别ID"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm('ruleForm')">下一步</el-button>
        <el-button @click="resetForm('ruleForm')">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
export default {
  data() {
    return {
      ruleForm: {
        categoryId: '',
        categoryName: ''
      },
      rules: {
        categoryId: [
          {required: true, message: '请输入类别ID', trigger: 'blur'},
        ]
      }
    };
  },
  methods: {
    getPreRuleForm() {
      let ruleFormString = localStorage.getItem('ruleForm');
      let preRuleForm = JSON.parse(ruleFormString);

      if (preRuleForm && preRuleForm.categoryId) {
        this.ruleForm.categoryId = preRuleForm.categoryId;
      }
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          // 检查填写的类别id是否有效
          let url = 'http://localhost:9080/categories/' + this.ruleForm.categoryId;
          console.log('url = ' + url);
          this.axios
              .create({'headers': {'Authorization': localStorage.getItem('jwt')}})
              .get(url).then((response) => {
            let responseBody = response.data;
            if (responseBody.state == 20000) {
              if (responseBody.data.isParent == 1) {
                this.$message.error('错误：选择的类别必须不包含子级类别！');
              } else {
                this.ruleForm.categoryName = responseBody.data.name;

                let ruleFormString = JSON.stringify(this.ruleForm);
                localStorage.setItem('ruleForm', ruleFormString);
                this.$router.push('spu-add-new2');
              }
            } else {
              this.$message.error(responseBody.message);
            }
          });
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    }
  },
  mounted() {
    this.getPreRuleForm();
  }
}
</script>

<style scoped>
</style>